#!/usr/bin/python

from optparse import OptionParser
import sys, os
import re
import StringIO



"""
seq_identifiers_unmap.py

"""

from optparse import OptionParser
import sys, os
import StringIO


# add self to search path for testing
if __name__ == '__main__':
    exe_path = os.path.split(os.path.abspath(sys.argv[0]))[0]
    python_module_path = os.path.abspath(os.path.join(exe_path,"..", "python_modules"))
    sys.path.append(python_module_path)

    # script name without the py
    exe_name = os.path.splitext(os.path.split(sys.argv[0])[1])[0]
else:
    myname = __name__

#
#   my own modules
# 
from general_util import die_error


usage = "usage: %prog --map_identifiers IDENTIFIERS.MAP < abbreviated.results > correct.results\n" + \
        "Converts a file using abbreviated identifiers (generated by seq_extract) "+\
        "back to their originals."
parser = OptionParser(version="%prog 1.0", usage=usage)
parser.add_option("-m", "--map_identifiers", dest="map_identifiers",
                  metavar="FILE", 
                  type="string",
                  help="File contain tab delimited columns of sequence identifiers and the "
                        "shortened forms (VWXYZ000xx) used to represent them to programmes "
                        "like phylip.")
parser.add_option("-r", "--reverse", dest="reverse",
                    action="store_true", default=False,
                    help="Map in the reverse direction.")
parser.set_defaults(map_identifiers = "") 

# get help string
f =StringIO.StringIO()
parser.print_help(f)
helpstr = f.getvalue()
(options, args) = parser.parse_args()

# mandatory options
if options.map_identifiers == "":
    die_error("Please specify a file in --map_identifiers.\n\n"+helpstr)

map_file = open(options.map_identifiers)
identifier_map = dict()
for line_num, line in enumerate(map_file):
    line = line.rstrip()
    if not len(line):
        continue
    short_name, original_name = line.split('\t')
    if options.reverse == True:
        short_name, original_name = original_name, short_name
    if original_name == None:
        die_error("Line #%d is not in tab-delimited 2-columnar format.\n[%s]" % (line_num, line))
    #print ">%s<\t>%s<"% ( short_name, original_name)
    identifier_map[short_name] = original_name


identifiers = identifier_map.keys()
identifiers.sort(key = lambda x: len(x), reverse=True)
identifier_str = "|".join(identifiers)
    
import re
regex = re.compile(identifier_str)
def lookup_identifier (match):
    short_id = match.group()
    if short_id not in identifier_map:
        die_error("The identifier %s was not found in the map file [%s]" 
                            % (short_id, options.map_identifiers))
    return identifier_map[short_id]

for line in sys.stdin:
    sys.stdout.write(regex.sub(lookup_identifier, line))
